package com.yxjx.duoxue.payment;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.course.CourseListActivity;
import com.yxjx.duoxue.customview.MyProgressDialog;
import com.yxjx.duoxue.customview.autolist.AutoListView;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnLoadListener;
import com.yxjx.duoxue.customview.autolist.AutoListView.OnRefreshListener;
import com.yxjx.duoxue.datamodel.DMOrder;
import com.yxjx.duoxue.datamodel.DMOrderListItem;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.utils.UIHelper;

public class MyOrderList extends BaseActionBarActivity implements OnRefreshListener,
		OnLoadListener {
	
	public static final int MSG_CODE_MODIFY_STATUS = 1;
	
	public static final int PAGE_ACTIVITY_NUM = 20;
	
	private MyOrderListAdapter mAdapter;
	private AutoListView mList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_order_list);
		customizeActionBarTitle("我购买的课程");
		mList = (AutoListView) findViewById(R.id.list);
		mAdapter = new MyOrderListAdapter();
		mList.setAdapter(mAdapter);
		mList.setOnRefreshListener(this);
		mList.setOnLoadListener(this);
		mList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 >= mAdapter.getCount() + 1 || arg2 == 0) {
					return;
				}
				
				DMOrderListItem order = mAdapter.getData().get(arg2 - 1);
				Intent intent = new Intent(getApplicationContext(), OrderInfoActivity.class);
				intent.putExtra(Yx.KEY_ORDER_ID, order.getId());
				startActivityForResult(intent, MSG_CODE_MODIFY_STATUS);
			}
		});
		
		
//		dialog = MyProgressDialog.showFullWindow(this, "", "加载中...");
//		dialog = MyProgressDialog.createLoadingDialog(this, "加载中...");
//		dialog.show();
		requestAllItems();
	}

	@Override
	public void onLoad() {
		requestsMoreItems();
	}


	@Override
	public void onRefresh() {
		requestAllItems();
		
	}
	
	class MyOrderListAdapter extends BaseAdapter {
		
		private ArrayList<DMOrderListItem> mDatas = new ArrayList<DMOrderListItem>();
		
		public ArrayList<DMOrderListItem> getData() {
			return mDatas;
		}
		
		public void addData(ArrayList<DMOrderListItem> result) {
			mDatas.addAll(result);
			notifyDataSetChanged();
			showEmptyInCase();
		}

		public void setData(ArrayList<DMOrderListItem> data) {
			mDatas = data;
			notifyDataSetChanged();
			showEmptyInCase();
		}

		@Override
		public int getCount() {
			return mDatas == null ? 0 : mDatas.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret;
			if (arg1 == null) {
				ret = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_order_list, null);
			} else {
				ret = arg1;
			}
			DMOrderListItem item = mDatas.get(arg0);
			UIHelper.asyncLoadImage((ImageView) ret.findViewById(R.id.icon), item.getCourse().getHeadImageUrl(), R.drawable.default_icon);
			UIHelper.setText(ret, R.id.course_name, item.getCourse().getCourseName());
			UIHelper.setText(ret, R.id.product_name, item.getProductName());
			UIHelper.setText(ret, R.id.product_price, "总价：" + item.getDiscountPrice() + " 元，数量：1");// + item.getProductCount());
			UIHelper.setText(ret, R.id.product_status, item.getOrderStatusDes());
			int supportBook = item.getCourse().getSupportBook();
			ret.findViewById(R.id.free_auditon).setVisibility(supportBook == 1 ? 
					View.VISIBLE : View.GONE);
			return ret;
		}
		
	}
	
	private Handler mHandler = new Handler() {
    	@Override
    	public void handleMessage(android.os.Message msg) {
    		ArrayList<DMOrderListItem> result = (ArrayList<DMOrderListItem>) msg.obj;
    		switch (msg.what) {
			case AutoListView.REFRESH:
				removeMessages(AutoListView.REFRESH);
				mAdapter.setData(result);
				mList.onRefreshComplete();
				// try to progress dialog
				dismissProgressDialog();
				resetScroll();
				break;
			case AutoListView.LOAD:
				removeMessages(AutoListView.LOAD);
				mAdapter.addData(result);
				mList.onRefreshComplete();
				dismissProgressDialog();
				break;
			default:
				break;
			}
    		mList.setResultSize(result == null ? 0 : result.size());
    	}
    };
	
	class RequestOrderListTask extends AsyncTask<String, Integer, ArrayList<DMOrderListItem>>{

		private Integer mCallbackId;

		@Override
		protected ArrayList<DMOrderListItem> doInBackground(String... arg0) {
			UserLoginResponse ulRsp = UserLoginResponse.getInstance(getApplicationContext());
			if (ulRsp == null) {
				// TODO login
			}
			
			String paramStr = arg0[0];
			mCallbackId = Integer.valueOf(arg0[1]);
			JSONObject param = null;
			try {
				param = new JSONObject(paramStr);
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			
			try {
				return UserReg.requestOrderList(ulRsp, param, MyOrderList.this);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(ArrayList<DMOrderListItem> result) {
			super.onPostExecute(result);
			mHandler.sendMessage(mHandler.obtainMessage(mCallbackId, result));
		}
	}
	
	private void requestItemsByParams(JSONObject params, int callbackId) {
		RequestOrderListTask task = new RequestOrderListTask();
		task.execute(params.toString(), "" + callbackId);
	}
	
	private void requestsMoreItems() {
		JSONObject param = new JSONObject();
		int startIndex = mAdapter.getCount() + 1;
		try {
			param.put("startIndex", "" + startIndex);
			param.put("count","20");
			param.put("time", "" + System.currentTimeMillis());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		requestItemsByParams(param, AutoListView.LOAD);
	}
	
	private void requestAllItems() {
		JSONObject param = new JSONObject();
		try {
			param.put("startIndex", "1");
			param.put("count","20");
			param.put("time", "" + System.currentTimeMillis());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		requestItemsByParams(param, AutoListView.REFRESH);
	}

	private void resetScroll() {
		mList.post(new Runnable() {
			
			@Override
			public void run() {
				mList.setSelection(0);
			}
		});
	}

	private void dismissProgressDialog() {

		findViewById(R.id.root).setVisibility(View.VISIBLE);
		findViewById(R.id.loading).setVisibility(View.INVISIBLE);
	}
	
	ProgressDialog dialog;
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO 修改List订单的状态
		super.onActivityResult(arg0, arg1, arg2);
		switch (arg0) {
		case MSG_CODE_MODIFY_STATUS:
			if (arg1 == OrderInfoActivity.RESULT_CODE_REFUND_OK
					|| arg1 == OrderInfoActivity.RESULT_CODE_PAY_SCHOOL) {
				DMOrder order = (DMOrder) arg2
						.getSerializableExtra(Yx.KEY_ORDER_OBJECT);
				updateList(order, mAdapter.getData());
			}
			break;
		default:
			break;
		}
	}
	
	private void updateList(DMOrder data, ArrayList<DMOrderListItem> list) {
		for (DMOrderListItem listItem : list) {
			if (data.getId().equals(listItem.getId())) {
				listItem.setOrderStatusDes(data.getOrderStatusDes());
				mAdapter.notifyDataSetInvalidated();
				break;
			}
		}
	}
	
	private void showEmptyInCase() {
		if (mAdapter != null && mAdapter.getCount() > 0) {
			findViewById(R.id.list).setVisibility(View.VISIBLE);
			findViewById(R.id.empty).setVisibility(View.INVISIBLE);
		} else {
			findViewById(R.id.empty).setVisibility(View.VISIBLE);
			findViewById(R.id.list).setVisibility(View.INVISIBLE);
		}
	}
	
	public void toFind(View view) {
		UIHelper.LoadingActivity(this, new Intent(getApplicationContext(),
				CourseListActivity.class));
		finish();
	}
	
}
